<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="任务名称" prop="taskName">
        <el-input 
          v-model="queryParams.taskName" 
          placeholder="请输入任务名称" 
          clearable 
          @keyup.enter.native="handleQuery" 
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="时间范围" prop="dateRange">
        <el-date-picker
          v-model="queryParams.dateRange"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="yyyy-MM-dd HH:mm:ss"
          style="width: 350px"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 工具栏 -->
    <el-row :gutter="10" class="mb8">
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 任务列表表格 -->
    <el-table 
      v-loading="loading" 
      :data="taskList" 
      border 
      stripe 
      highlight-current-row
      @sort-change="handleSortChange"
    >
      <el-table-column label="任务名称" align="center" prop="taskName" min-width="180" show-overflow-tooltip sortable="custom" />
      <el-table-column label="区域类型" align="center" width="100">
        <template slot-scope="scope">
          <el-tag :type="getAreaTypeTagColor(scope.row.openUnit)" size="small">
            {{ getAreaTypeName(scope.row.openUnit) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="startTime" min-width="150" sortable="custom" />
      <el-table-column label="结束时间" align="center" prop="endTime" min-width="150" sortable="custom" />
      <el-table-column label="开放对象" align="center" min-width="120">
        <template slot-scope="scope">
          <el-tag size="small" v-for="(target, index) in getOpenTargets(scope.row.openTarget)" :key="index" style="margin: 2px">
            {{ target }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="区域" align="center" min-width="200">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.createUser" type="warning" size="small">
            <i class="el-icon-user"></i> {{ getUserNicknameById(scope.row.createUser) }}
          </el-tag>
          <el-tag v-if="scope.row.createDept" type="info" size="small">
            <i class="el-icon-office-building"></i> {{ getDeptNameById(scope.row.createDept) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="280">
        <template slot-scope="scope">
          <el-button 
            size="mini" 
            type="text" 
            plain
            icon="el-icon-view" 
            @click="viewResult(scope.row)"
            :disabled="!canViewResult(scope.row)"
          >查看填写情况</el-button>
          <el-button 
            type="text" 
            plain 
            icon="el-icon-download" 
            size="mini"
            @click="handleExport(scope.row)"
          >导出</el-button>
        
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination 
      v-show="total > 0" 
      :total="total" 
      :page.sync="queryParams.pageNum" 
      :limit.sync="queryParams.pageSize"
      layout="total, sizes, prev, pager, next, jumper" 
      @pagination="getList"
    />

    <!-- 测评结果抽屉 -->
    <el-drawer 
      :title="drawerTitle" 
      :visible.sync="resultDrawerVisible" 
      direction="rtl" 
      size="85%"
      :destroy-on-close="true" 
      class="result-drawer" 
      :before-close="handleDrawerClose"
    >
      <div class="drawer-container">
        <!-- 主要内容区域 -->
        <splitpanes :horizontal="false" class="default-theme" style="height: calc(100% - 120px)">
          <!-- 区域树面板 -->
          <pane :size="deptPaneSize" v-show="showDeptPane">
            <div class="dept-panel">
              <div class="panel-header">
                <h4><i class="el-icon-office-building"></i> 区域列表</h4>
              </div>
              <div class="panel-content">
                <el-table 
                  v-loading="deptLoading" 
                  :data="filteredDeptList" 
                  border 
                  stripe 
                  highlight-current-row
                  @row-click="handleDeptRowClick"
                  :row-class-name="getDeptRowClassName"
                  style="width: 100%"
                  size="mini"
                  row-key="deptId"
                  :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
                  empty-text="暂无区域数据"
                >
                  <el-table-column label="区域名称" prop="label" show-overflow-tooltip>
                    <template slot-scope="scope">
                      <i :class="getDeptIcon(scope.row)"></i>
                      <span style="margin-left: 5px">{{ scope.row.deptName }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="类型" prop="type" width="60" align="center">
                    <template slot-scope="scope">
                      <el-badge :value="getDeptTypeName(scope.row.type)" type="primary" />

                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </pane>
          
          <!-- 用户列表面板 -->
          <pane :size="userPaneSize">
            <div class="user-panel">
              <div class="panel-header">
                <h4><i class="el-icon-user"></i> {{ selectedDeptName ? `${selectedDeptName} - 用户列表` : '用户列表' }}</h4>
                <!-- 用户搜索表单 -->
                <el-form 
                  :model="resultQueryParams" 
                  ref="resultQueryForm" 
                  size="small" 
                  :inline="true"
                  v-show="showResultSearch" 
                  label-width="68px"
                  style="margin-top: 10px"
                >
                  <el-form-item label="用户名称" prop="userName">
                    <el-input 
                      v-model="resultQueryParams.userName" 
                      placeholder="请输入用户名称" 
                      clearable 
                      style="width: 180px"
                      @keyup.enter.native="handleResultQuery" 
                    />
                  </el-form-item>
                
                  <el-form-item>
                    <el-button type="primary" icon="el-icon-search" size="mini" @click="handleResultQuery">搜索</el-button>
                    <el-button icon="el-icon-refresh" size="mini" @click="resetResultQuery">重置</el-button>
                  </el-form-item>
                </el-form>
              </div>
              
              <div class="panel-content">

                <!-- 用户列表表格 -->
                <el-table 
                  v-loading="resultLoading" 
                  :data="userList" 
                  border 
                  stripe 
                  highlight-current-row
                  style="margin-top: 10px"
                  empty-text="暂无用户数据"
                  @sort-change="handleUserSortChange"
                >
                  <el-table-column type="index" label="序号" width="50" align="center" />
                  <el-table-column label="用户名称" align="center" prop="userName" min-width="100" show-overflow-tooltip sortable="custom" />
                  <el-table-column label="用户昵称" align="center" prop="nickName" min-width="100" show-overflow-tooltip />
                  <el-table-column label="区域" align="center" prop="dept.deptName" min-width="120" show-overflow-tooltip />
                  <el-table-column label="填写状态" align="center" width="100">
                    <template slot-scope="scope">
                      <el-tag :type="getTaskStatusType(scope.row.taskStatus)" size="small">
                        {{ getTaskStatusText(scope.row.taskStatus) }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" align="center" width="200">
                    <template slot-scope="scope">
                      <el-button 
                        v-if="scope.row.taskStatus && scope.row.taskStatus != '0'" 
                        type="primary" 
                        size="mini" 
                        icon="el-icon-view"
                        @click="viewUserQuestionnaire(scope.row)"
                      >查看问卷</el-button>
                      <!-- <el-button 
                        v-if="scope.row.taskStatus && scope.row.taskStatus != '0'" 
                        type="success" 
                        size="mini" 
                        icon="el-icon-document"
                        @click="viewUserReport(scope.row)"
                      >查看报告</el-button> -->
                    </template>
                  </el-table-column>
                </el-table>

                <!-- 用户列表分页 -->
                <pagination 
                  v-show="resultTotal > 0" 
                  :total="resultTotal" 
                  :page.sync="resultQueryParams.pageNum" 
                  :limit.sync="resultQueryParams.pageSize" 
                  @pagination="getUserList"
                  style="margin-top: 10px"
                />
              </div>
            </div>
          </pane>
        </splitpanes>
      </div>
    </el-drawer>


  </div>
</template>

<script>
import { listAssess, getDeptTree, changeUpdateAssess } from "@/api/system/assess";
import { listUser, deptTreeSelect, getUser } from "@/api/system/user";
import { listDept } from "@/api/system/dept";
import { Splitpanes, Pane } from "splitpanes";
import "splitpanes/dist/splitpanes.css";

export default {
  name: "AssessmentTasks",
  components: { Splitpanes, Pane },
  data() {
    return {
      // 加载状态
      loading: true,
      resultLoading: false,
      deptLoading: false,
      
      // 显示控制
      showSearch: true,
      showResultSearch: true,
      showDeptPane: true,
      
      // 面板大小
      deptPaneSize: 25,
      userPaneSize: 75,
      
      // 数据总数
      total: 0,
      resultTotal: 0,
      
      // 任务列表
      taskList: [],
      
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        taskName: null,
        status: null,
        openUnit: null,
        dateRange: null,
        startTime: null,
        endTime: null,
        orderByColumn: null,
        isAsc: null
      },
      
      // 结果查询参数
      resultQueryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        deptId: undefined,
        taskId: undefined,
        taskStatus: undefined,
        createUser: undefined,
        orderByColumn: null,
        isAsc: null
      },
      
      // 抽屉相关
      resultDrawerVisible: false,
      currentTaskId: null,
      currentTaskName: "",
      taskInfo: {},
      
      // 区域相关
      deptOptions: [],
      filteredDeptList: [],
      selectedDeptId: null,
      selectedDeptName: null,
      deptQueryParams: {
        deptName: undefined
      },
      
      // 用户列表
      userList: [],
      
      // 缓存数据
      userCache: {},
      deptCache: {},
      

    };
  },
  
  computed: {
    // 抽屉标题
    drawerTitle() {
      return `测评结果 - ${this.currentTaskName}`;
    },
    
    // 判断当前是否为个人区域
    isPersonalArea() {
      return this.taskInfo && this.taskInfo.createUser;
    }
  },
  
  watch: {
    // 根据名称筛选区域表格
    'deptQueryParams.deptName'(val) {
      this.filterDeptList();
    }
  },
  
  created() {
    this.initializeData();
  },
  
  methods: {
    getDeptTypeName(type){
      let openUnitOptions = [
      { dictLabel: '市级', dictValue: '1' },
      { dictLabel: '区县', dictValue: '2' },
      { dictLabel: '教育局', dictValue: '3' },
      { dictLabel: '学校', dictValue: '4' },
      { dictLabel: '年级', dictValue: '5' },
      { dictLabel: '班级', dictValue: '6' },
      { dictLabel: '个人', dictValue: '7' }
    ];

    let item=openUnitOptions.find(item=>item.dictValue==type);
    if (item?.dictLabel) {
    return item?.dictLabel;
      
    }else{
      return '机构'
    }


    },
    /** 初始化数据 */
    async initializeData() {
      try {
        await Promise.all([
          this.getAllUsers(),
          this.getAllDepts(),
          this.getList()
        ]);
      } catch (error) {
        console.error('初始化数据失败:', error);
        this.$modal.msgError('初始化数据失败，请刷新页面重试');
      }
    },
    
    /** 刷新数据 */
    async refreshData() {
      this.loading = true;
      try {
        await this.initializeData();
        this.$modal.msgSuccess('数据刷新成功');
      } catch (error) {
        this.$modal.msgError('数据刷新失败');
      } finally {
        this.loading = false;
      }
    },
    
    /** 获取所有部门数据 */
    async getAllDepts() {
      try {
        const response = await listDept();
        if (response && response.data) {
          const deptMap = {};
          this.processDeptData(response.data, deptMap);
          this.deptCache = deptMap;
        }
      } catch (error) {
        console.error('获取部门数据失败:', error);
      }
    },
    
    /** 递归处理部门数据 */
    processDeptData(depts, deptMap) {
      if (!depts || !Array.isArray(depts)) return;
      
      depts.forEach(dept => {
        if (dept && dept.deptId !== undefined) {
          deptMap[String(dept.deptId)] = dept;
          if (dept.children && Array.isArray(dept.children)) {
            this.processDeptData(dept.children, deptMap);
          }
        }
      });
    },
    
    /** 获取所有用户数据 */
    async getAllUsers() {
      try {
        const response = await listUser({ pageSize: 9999 });
        if (response && response.rows) {
          const userMap = {};
          response.rows.forEach((user) => {
            if (user && user.userId !== undefined) {
              userMap[String(user.userId)] = user;
            }
          });
          this.userCache = userMap;
        }
      } catch (error) {
        console.error('获取用户数据失败:', error);
      }
    },
    
    /** 查询任务列表 */
    async getList() {
      this.loading = true;
      try {
        const response = await listAssess(this.queryParams);
        this.taskList = response.rows || [];
        this.total = response.total || 0;
        
        // 处理任务状态
        this.processTaskStatus();
        
      } catch (error) {
        console.error('获取任务列表失败:', error);
        this.$modal.msgError('获取任务列表失败');
      } finally {
        this.loading = false;
      }
    },
    
    /** 处理任务状态 */
    processTaskStatus() {
      this.taskList.forEach((task) => {
        const now = new Date();
        const startTime = new Date(task.startTime);
        const endTime = new Date(task.endTime);
        
        if (now < startTime) {
          task.status = "0"; // 未开始
        } else if (now > endTime) {
          task.status = "2"; // 已完成
        } else {
          task.status = "1"; // 进行中
        }
        
        task.isSubmitted = task.taskStatus !== 0;
      });
    },
    
    /** 搜索按钮操作 */
    handleQuery() {
      // 处理日期范围
      if (this.queryParams.dateRange && this.queryParams.dateRange.length === 2) {
        this.queryParams.startTime = this.queryParams.dateRange[0];
        this.queryParams.endTime = this.queryParams.dateRange[1];
      } else {
        this.queryParams.startTime = null;
        this.queryParams.endTime = null;
      }
      
      this.queryParams.pageNum = 1;
      this.getList();
    },
    
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      // 重置日期范围相关字段
      this.queryParams.dateRange = null;
      this.queryParams.startTime = null;
      this.queryParams.endTime = null;
      this.handleQuery();
    },
    
    /** 排序变化处理 */
    handleSortChange({ column, prop, order }) {
      this.queryParams.orderByColumn = prop;
      this.queryParams.isAsc = order === 'ascending' ? 'asc' : 'desc';
      this.getList();
    },
    
    /** 用户列表排序变化处理 */
    handleUserSortChange({ column, prop, order }) {
      this.resultQueryParams.orderByColumn = prop;
      this.resultQueryParams.isAsc = order === 'ascending' ? 'asc' : 'desc';
      this.getUserList();
    },
    
    /** 导出操作 */
    handleExport(row) {
      this.download(
        `system/assess/task/overview/export?taskId=${row.id}`,
        {
          ...this.queryParams,
          taskId: row.id,
        },
        `assess_${row.taskName}_${new Date().getTime()}.xlsx`
      );
    },
    

    
    /** 查询区域下拉树结构 */
    async getDeptTree() {
      try {
        this.deptLoading = true;
        
        const response = await listDept();
        if (!response || !response.data) {
          this.$modal.msgError('获取区域数据失败');
          return;
        }
        
        this.deptOptions = this.handleTree(response.data,"deptId");

        // 部门数据已加载

        await this.initializeDeptSelection();
        
      } catch (error) {
        console.error('获取区域树数据失败:', error);
        this.$modal.msgError('获取区域数据失败，请稍后重试');
      } finally {
        this.deptLoading = false;
      }
    },
    

    
    /** 初始化区域选择 */
    async initializeDeptSelection() {
      await this.$nextTick();
      
        // 初始化时跳过selectedDeptId过滤，获取所有可用的部门
        this.filterDeptList(true);
        
        if (this.filteredDeptList && this.filteredDeptList.length > 0) {
          const firstNode = this.getFirstParentNode(this.filteredDeptList);
  
          if (firstNode && firstNode.deptId) {
            this.selectedDeptId = firstNode.deptId;
            this.selectedDeptName = firstNode.deptName;
            this.resultQueryParams.deptId = firstNode.deptId;
            // 设置selectedDeptId后重新过滤，只显示当前部门及其子级
            this.filterDeptList();
            await this.getUserList();
          } else {
            this.$modal.msgWarning('未找到可用的区域节点');
          }
        } else {
          this.$modal.msgWarning('没有可显示的区域数据');
        }
    },    
    
    /** 递归过滤区域树 */
    filterDeptsByIds(depts, allowedIds) {
      if (!Array.isArray(depts) || !Array.isArray(allowedIds) || allowedIds.length === 0) {
        return [];
      }
      
      const allowedIdSet = new Set(allowedIds.map(id => String(id)));
      const result = [];
      
      for (const dept of depts) {
        if (!dept || dept.deptId === undefined || dept.deptId === null) {
          continue;
        }
        
        const deptId = String(dept.deptId);
        const isAllowed = allowedIdSet.has(deptId);
        
        if (isAllowed) {
          result.push(this.deepCloneDept(dept));
        } else {
          if (dept.children && Array.isArray(dept.children) && dept.children.length > 0) {
            const filteredChildren = this.filterDeptsByIds(dept.children, allowedIds);
            if (filteredChildren.length > 0) {
              result.push(...filteredChildren);
            }
          }
        }
      }
      
      return result;
    },
    
    /** 深拷贝部门对象 */
    deepCloneDept(dept) {
      if (!dept) return null;
      
      try {
        return JSON.parse(JSON.stringify(dept));
      } catch (error) {
        console.error('深拷贝部门对象失败:', error);
        return { ...dept };
      }
    },
    
    /** 过滤区域列表 */
    filterDeptList(skipSelectedFilter = false) {
      if (!this.deptOptions) {
        this.filteredDeptList = [];
        return;
      }
      
      this.deptLoading = true;
      
      let baseData = this.deptOptions;
      
      if (this.currentTaskId && this.taskInfo && this.taskInfo.createDept) {
        baseData = this.getFilteredDeptsByCreateDept(this.deptOptions);
      }

      // 根据selectedDeptId过滤，只显示当前选中部门及其下级部门
      // 但是如果已经通过createDept过滤了，就不再进行selectedDeptId过滤
      if (this.selectedDeptId && !skipSelectedFilter && !(this.currentTaskId && this.taskInfo && this.taskInfo.createDept)) {
        baseData = this.filterDeptTreeBySelectedId(baseData, this.selectedDeptId);
      }

      if (this.deptQueryParams.deptName) {
        this.filteredDeptList = this.filterTreeByName(baseData, this.deptQueryParams.deptName);
      } else {
        this.filteredDeptList = baseData;
      }
      
      this.deptLoading = false;
    },
    
    /** 根据选中的部门ID过滤树形数据 */
    filterDeptTreeBySelectedId(depts, selectedId) {
      if (!depts || !selectedId) return depts;
      
      // 递归查找目标部门
      const findTargetDept = (deptList) => {
        for (const dept of deptList) {
          if (!dept || dept.deptId === undefined || dept.deptId === null) continue;
          
          const deptId = dept.deptId.toString();
          
          if (deptId === selectedId.toString()) {
            // 找到目标部门，返回该部门及其所有子部门
            return [{ ...dept }];
          }
          
          // 递归查找子部门
          if (dept.children && dept.children.length) {
            const found = findTargetDept(dept.children);
            if (found.length > 0) {
              return found;
            }
          }
        }
        return [];
      };
      
      return findTargetDept(depts);
    },
    
    /** 根据createDept获取过滤后的部门数据 */
    getFilteredDeptsByCreateDept(depts) {
      if (!this.taskInfo || !this.taskInfo.createDept) return depts;
      
      let deptIds = [];
      const createDept = this.taskInfo.createDept;
      
      if (Array.isArray(createDept)) {
        deptIds = createDept.map(id => id.toString());
      } else if (typeof createDept === 'string' && createDept.includes(',')) {
        deptIds = createDept.split(',').map(id => id.trim());
      } else if (createDept) {
        deptIds = [createDept.toString()];
      }
      
      // 使用新的过滤方法，只返回指定部门及其子级
      return this.filterDeptTreeByCreateDeptIds(depts, deptIds);
    },
    
    /** 根据createDept部门ID过滤树形数据，只返回指定部门及其子级 */
    filterDeptTreeByCreateDeptIds(depts, createDeptIds) {
      if (!depts || !createDeptIds || !createDeptIds.length) return [];
      
      // 递归查找指定的createDept部门
      const findCreateDept = (deptList) => {
        for (const dept of deptList) {
          if (!dept || dept.deptId === undefined || dept.deptId === null) continue;
          
          const deptId = dept.deptId.toString();
          
          if (createDeptIds.includes(deptId)) {
            // 找到createDept部门，返回该部门及其完整的子部门树
            return this.deepCloneDept(dept);
          }
          
          // 递归查找子部门
          if (dept.children && dept.children.length) {
            const found = findCreateDept(dept.children);
            if (found) {
              return found;
            }
          }
        }
        
        return null;
      };
      
      const foundDept = findCreateDept(depts);
      return foundDept ? [foundDept] : [];
    },
    
    /** 根据部门ID过滤树形数据 */
    filterDeptTreeByIds(depts, allowedIds) {
      if (!depts || !allowedIds || !allowedIds.length) return [];
      
      const result = [];
      
      for (const dept of depts) {
        if (!dept || dept.deptId === undefined || dept.deptId === null) continue;
        const deptId = dept.deptId.toString();
        
        if (allowedIds.includes(deptId)) {
          result.push({ ...dept });
        } else {
          if (dept.children && dept.children.length) {
            const filteredChildren = this.filterDeptTreeByIds(dept.children, allowedIds);
            if (filteredChildren.length > 0) {
              result.push({
                ...dept,
                children: filteredChildren
              });
            }
          }
        }
      }
      
      return result;
    },
    
    /** 根据名称过滤树形数据 */
    filterTreeByName(tree, deptId) {
      if (!tree || !deptId) return tree;
      
      const searchLower = deptId.toLowerCase();
      const result = [];
      
      for (const node of tree) {
        const nodeMatches = node.label && node.label.toLowerCase().includes(searchLower);
        let filteredChildren = [];
        
        if (node.children && node.children.length) {
          filteredChildren = this.filterTreeByName(node.children, deptId);
        }
        
        if (nodeMatches || filteredChildren.length > 0) {
          result.push({
            ...node,
            children: filteredChildren
          });
        }
      }
      
      return result;
    },
    
    /** 处理区域查询 */
    handleDeptQuery() {
      this.filterDeptList();
    },
    
    /** 获取树形数据中的第一个叶子节点 */
    getFirstLeafNode(tree) {
      if (!tree || !tree.length) return null;
      
      const firstNode = tree[0];
      if (firstNode.children && firstNode.children.length > 0) {
        return this.getFirstLeafNode(firstNode.children);
      }
      
      return firstNode;
    },
    
    /** 获取树形数据中的第一个父级节点（有子节点的节点） */
    getFirstParentNode(tree) {
      if (!tree || !tree.length) return null;
      
      const firstNode = tree[0];
      // 如果第一个节点有子节点，则返回它作为父级节点
      if (firstNode.children && firstNode.children.length > 0) {
        return firstNode;
      }
      
      // 如果第一个节点没有子节点，则继续查找其他节点
      for (let i = 1; i < tree.length; i++) {
        if (tree[i].children && tree[i].children.length > 0) {
          return tree[i];
        }
      }
      
      // 如果都没有子节点，则返回第一个节点
      return firstNode;
    },
    
    /** 处理表格行点击事件 */
    handleDeptRowClick(row) {
      this.selectedDeptId = row.deptId;
      this.selectedDeptName = row.deptName;
      this.resultQueryParams.deptId = row.deptId;
      // 重新过滤区域列表，只显示当前选中部门及其子级
      this.filterDeptList();
      this.getUserList();
    },
    
    /** 获取表格行的类名 */
    getDeptRowClassName({ row }) {
      return this.selectedDeptId === row.deptId ? 'current-row' : '';
    },
    
    /** 获取部门图标 */
    getDeptIcon(dept) {
      // 根据部门类型返回不同图标
      const level = dept.level || 0;
      const iconMap = {
        0: 'el-icon-office-building',
        1: 'el-icon-school',
        2: 'el-icon-user-solid',
        3: 'el-icon-user'
      };
      return iconMap[level] || 'el-icon-folder';
    },
    
    /** 查询用户列表 */
    async getUserList() {
      if (!this.currentTaskId) {
        this.$modal.msgWarning("任务ID不能为空");
        return;
      }
      
      try {
        this.resultLoading = true;
        
        if (this.resultQueryParams.createUser) {
          await this.getUserListByCreateUser();
          return;
        }
        
        await this.getUserListByDept();
        
      } catch (error) {
        console.error('获取用户列表失败:', error);
        this.$modal.msgError('获取用户列表失败，请稍后重试');
        this.userList = [];
        this.resultTotal = 0;
      } finally {
        this.resultLoading = false;
      }
    },
    
    /** 根据createUser参数获取用户列表 */
    async getUserListByCreateUser() {
      try {
        const userIds = this.parseUserIds(this.resultQueryParams.createUser);
        
        if (!userIds || userIds.length === 0) {
          this.userList = [];
          this.resultTotal = 0;
          return;
        }
        
        const userPromises = userIds.map(userId => 
          getUser(userId).catch(error => {
            console.warn(`获取用户${userId}信息失败:`, error);
            return null;
          })
        );
        
        const responses = await Promise.all(userPromises);
        
        const allUsers = responses
          .filter(res => res && res.data)
          .map(res => res.data);
        
        if (allUsers.length === 0) {
          this.userList = [];
          this.resultTotal = 0;
          return;
        }
        
        const { pageNum = 1, pageSize = 10 } = this.resultQueryParams;
        const startIndex = (pageNum - 1) * pageSize;
        const endIndex = startIndex + pageSize;
        const pagedUsers = allUsers.slice(startIndex, endIndex);
        
        await this.enrichUsersWithTaskStatus(pagedUsers);
        
        this.userList = pagedUsers;
        this.resultTotal = allUsers.length;
        
      } catch (error) {
        console.error('根据createUser获取用户列表失败:', error);
        throw error;
      }
    },
    
    /** 根据部门获取用户列表 */
    async getUserListByDept() {
      try {
        const params = this.buildUserQueryParams();
        const response = await listUser(params);
        
        if (!response) {
          throw new Error('API响应为空');
        }
        
        this.userList = response.rows || [];
        this.resultTotal = response.total || 0;
        
      } catch (error) {
        console.error('根据部门获取用户列表失败:', error);
        throw error;
      }
    },
    
    /** 解析用户ID列表 */
    parseUserIds(createUser) {
      if (!createUser) return [];
      
      try {
        if (typeof createUser === 'string') {
          return createUser.split(',').map(id => id.trim()).filter(id => id);
        } else if (Array.isArray(createUser)) {
          return createUser.map(id => String(id).trim()).filter(id => id);
        } else {
          return [String(createUser).trim()];
        }
      } catch (error) {
        console.error('解析用户ID失败:', error);
        return [];
      }
    },
    
    /** 构建用户查询参数 */
    buildUserQueryParams() {
      return {
        pageNum: this.resultQueryParams.pageNum || 1,
        pageSize: this.resultQueryParams.pageSize || 10,
        deptId: this.resultQueryParams.deptId,
        taskId: this.currentTaskId,
        userName: this.resultQueryParams.userName || undefined,
        phonenumber: this.resultQueryParams.phonenumber || undefined,
        taskStatus: this.resultQueryParams.taskStatus || undefined,
        orderByColumn: this.resultQueryParams.orderByColumn,
        isAsc: this.resultQueryParams.isAsc
      };
    },
    
    /** 为用户列表添加任务状态信息 */
    async enrichUsersWithTaskStatus(users) {
      if (!users || users.length === 0) return;
      
      try {
        const assessParams = {
          taskId: this.currentTaskId,
          userIds: users.map(u => u.userId).join(',')
        };
        
        const assessResponse = await listAssess(assessParams);
        
        const taskStatusMap = new Map();
        if (assessResponse && assessResponse.rows) {
          assessResponse.rows.forEach(item => {
            if (item.userId && item.taskStatus !== undefined) {
              taskStatusMap.set(item.userId, item.taskStatus);
            }
          });
        }
        
        users.forEach(user => {
          user.taskStatus = taskStatusMap.get(user.userId) || 0;
        });
        
      } catch (error) {
        console.error('获取用户任务状态失败:', error);
        users.forEach(user => {
          user.taskStatus = 0;
        });
      }
    },
    
    /** 搜索结果按钮操作 */
    handleResultQuery() {
      this.resultQueryParams.pageNum = 1;
      this.getUserList();
    },
    
    /** 重置结果查询 */
    resetResultQuery() {
      this.resultQueryParams = {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        deptId: this.resultQueryParams.deptId,
        taskId: this.currentTaskId,
        taskStatus: undefined,
        createUser: this.resultQueryParams.createUser,
        orderByColumn: null,
        isAsc: null
      };
      
      this.getUserList();
    },
    
    /** 查看结果 */
    async viewResult(row) {
      try {
        if (!row || !row.id) {
          this.$modal.msgError('任务信息无效');
          return;
        }
        
        this.currentTaskId = row.id;
        this.currentTaskName = row.taskName || "未知任务";
        this.taskInfo = row;
        this.resultDrawerVisible = true;
        
        this.resetResultQueryParams();
        this.resultQueryParams.taskId = row.id;
        
        if (row.createUser) {
          await this.handleCreateUserMode(row);
        } else {
          await this.handleCreateDeptMode();
        }
        
      } catch (error) {
        console.error('查看结果失败:', error);
        this.$modal.msgError('查看结果失败，请稍后重试');
      }
    },
    
    /** 处理createUser模式 */
    async handleCreateUserMode(row) {
      try {
        await this.$nextTick();
        
        this.showDeptPane = false;
        this.deptPaneSize = 0;
        this.userPaneSize = 100;
        
        this.resultQueryParams.createUser = row.createUser;
        await this.getUserList();
        
      } catch (error) {
        console.error('处理createUser模式失败:', error);
        throw error;
      }
    },
    
    /** 处理createDept模式 */
    async handleCreateDeptMode() {
      try {
        this.showDeptPane = true;
        this.deptPaneSize = 25;
        this.userPaneSize = 75;
        
        await this.getDeptTree();
        this.resetResultQuery();
        
      } catch (error) {
        console.error('处理createDept模式失败:', error);
        throw error;
      }
    },
    
    /** 重置结果查询参数 */
    resetResultQueryParams() {
      this.resultQueryParams = {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        deptId: undefined,
        taskId: undefined,
        taskStatus: undefined,
        createUser: undefined,
        orderByColumn: null,
        isAsc: null
      };
    },
    
    /** 处理抽屉关闭事件 */
    async handleDrawerClose() {
      try {
        this.resultDrawerVisible = false;
        
        this.currentTaskId = null;
        this.currentTaskName = '';
        this.taskInfo = {};
        this.selectedDeptId = null;
        
        this.resetResultQueryParams();
        
        this.userList = [];
        this.resultTotal = 0;
        
        this.deptOptions = [];
        this.filteredDeptList = [];
        
        this.showDeptPane = true;
        this.deptPaneSize = 25;
        this.userPaneSize = 75;
        
        await this.getList();
        
      } catch (error) {
        console.error('关闭抽屉时发生错误:', error);
        this.resultDrawerVisible = false;
      }
    },
    
    /** 刷新任务信息 */
    async refreshTaskInfo() {
      if (!this.currentTaskId) return;
      
      try {
        // 重新获取任务信息
        const response = await listAssess({ id: this.currentTaskId });
        if (response && response.rows && response.rows.length > 0) {
          this.taskInfo = response.rows[0];
          this.processTaskStatus();
        }
      } catch (error) {
        console.error('刷新任务信息失败:', error);
      }
    },
    
    /** 查看用户问卷 */
    viewUserQuestionnaire(user) {
      if (!this.currentTaskId) {
        this.$message.warning("请先选择任务");
        return;
      }
      
      window.open(
        `/questionnaire?scaleId=${this.taskInfo.scaleIds}&taskId=${this.currentTaskId}&userId=${user.userId}&viewType=question`,
        "_blank"
      );
    },
    
    /** 查看用户报告 */
    viewUserReport(user) {
      if (!this.currentTaskId) {
        this.$message.warning("请先选择任务");
        return;
      }
      
      window.open(
        `/detail?userId=${user.userId}&taskId=${this.currentTaskId}`,
        "_blank"
      );
    },
    
    /** 发送提醒 */
    async sendReminder(user) {
      try {
        // 这里可以调用发送提醒的API
        // await sendTaskReminder({ userId: user.userId, taskId: this.currentTaskId });
        this.$modal.msgSuccess(`已向用户 ${user.userName} 发送测评提醒`);
      } catch (error) {
        console.error('发送提醒失败:', error);
        this.$modal.msgError('发送提醒失败');
      }
    },
    
    // ========== 工具方法 ==========
    
    /** 根据用户ID获取用户昵称 */
    getUserNicknameById(userId) {
      if (!userId) return "";
      
      if (typeof userId === "string" && userId.includes(",")) {
        const userIds = userId.split(",").map((id) => id.trim());
        const userNames = userIds.map((id) => {
          const user = this.userCache[id];
          return user ? user.userName || user.nickName || id : id;
        });
        return userNames.join(", ");
      }
      
      const id = String(userId);
      const user = this.userCache[id];
      return user ? user.userName || user.nickName || id : id;
    },
    
    /** 根据部门ID获取部门名称 */
    getDeptNameById(deptId) {
      if (!deptId) return "";
      
      if (typeof deptId === "string" && deptId.includes(",")) {
        const deptIds = deptId.split(",").map((id) => id.trim());
        const deptNames = deptIds.map((id) => {
          const dept = this.deptCache[id];
          return dept ? dept.deptName || id : id;
        });
        return deptNames.join(", ");
      }
      
      const id = String(deptId);
      const dept = this.deptCache[id];
      return dept ? dept.deptName || id : id;
    },
    
    /** 获取开放对象列表 */
    getOpenTargets(openTarget) {
      if (!openTarget) return [];
      
      try {
        const targets = JSON.parse(openTarget);
        return Array.isArray(targets) ? targets : [targets];
      } catch (error) {
        return [openTarget];
      }
    },
    
    /** 获取区域类型名称 */
    getAreaTypeName(type) {
      const numType = type ? parseInt(type, 10) : 0;
      const typeMap = {
        1: '市级',
        2: '区县',
        3: '教育局',
        4: '学校',
        5: '年级',
        6: '班级',
        7: '个人'
      };
      return typeMap[numType] || '未知';
    },
    
    /** 获取区域类型标签颜色 */
    getAreaTypeTagColor(type) {
      const numType = type ? parseInt(type, 10) : 0;
      const colorMap = {
        1: 'danger',
        2: 'warning',
        3: 'info',
        4: 'primary',
        5: 'success',
        6: 'success',
        7: 'danger'
      };
      return colorMap[numType] || '';
    },
    
    /** 获取状态类型 */
    getStatusType(row) {
      const statusMap = {
        0: "info",
        1: "success",
        2: "warning"
      };
      return statusMap[row.status] || "info";
    },
    
    /** 获取状态文本 */
    getStatusText(row) {
      const statusMap = {
        0: "未开始",
        1: "进行中",
        2: "已完成"
      };
      return statusMap[row.status] || "未知";
    },
    
    /** 获取任务状态类型 */
    getTaskStatusType(taskStatus) {
      return taskStatus && taskStatus != '0' ? 'success' : 'info';
    },
    
    /** 获取任务状态文本 */
    getTaskStatusText(taskStatus) {
      return taskStatus && taskStatus != '0' ? '已填写' : '未填写';
    },
    
    /** 检查是否可以查看结果 */
    canViewResult(row) {
      return row && row.id;
    },
    
    /** 检查是否可以导出 */
    canExport(row) {
      return row && row.id && (row.participantCount > 0 || row.status === '2');
    },
    
    /** 获取参与率 */
    getParticipationRate(task) {
      if (!task || !task.totalCount || task.totalCount === 0) return 0;
      const rate = ((task.participantCount || 0) / task.totalCount * 100).toFixed(1);
      return parseFloat(rate);
    },
    
    /** 获取已完成数量 */
    getCompletedCount() {
      return this.userList.filter(user => user.taskStatus && user.taskStatus != '0').length;
    },
    
    /** 获取未完成数量 */
    getPendingCount() {
      return this.userList.filter(user => !user.taskStatus || user.taskStatus == '0').length;
    },
    
    /** 获取完成率 */
    getCompletionRate() {
      if (this.userList.length === 0) return 0;
      const rate = (this.getCompletedCount() / this.userList.length * 100).toFixed(1);
      return parseFloat(rate);
    }
  }
};
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.mb8 {
  margin-bottom: 8px;
}

/* 抽屉样式 */
.result-drawer {
  padding: 0;
}

.result-drawer ::v-deep .el-drawer__header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 20px;
  margin-bottom: 0;
  border-bottom: 1px solid #e6e6e6;
}

.result-drawer ::v-deep .el-drawer__title {
  color: white;
  font-size: 18px;
  font-weight: 600;
}

.result-drawer ::v-deep .el-drawer__close-btn {
  color: white;
  font-size: 20px;
}

.result-drawer ::v-deep .el-drawer__close-btn:hover {
  color: #f0f0f0;
}

.drawer-container {
  height: calc(100vh - 60px);
  overflow: hidden;
  padding: 0;
  background-color: #f8f9fa;
}

/* 面板样式 */
.dept-panel, .user-panel {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: white;
  margin: 10px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.panel-header {
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 15px 20px;
  border-bottom: 1px solid #e6e6e6;
  flex-shrink: 0;
}

.panel-header h4 {
  margin: 0;
  color: #2c3e50;
  font-size: 16px;
  font-weight: 600;
  display: flex;
  align-items: center;
}

.panel-header h4 i {
  margin-right: 8px;
  color: #667eea;
}

.panel-content {
  flex: 1;
  overflow: auto;
  padding: 15px;
}

/* 表格样式优化 */
.panel-content ::v-deep .el-table {
  border-radius: 6px;
  overflow: hidden;
}

.panel-content ::v-deep .el-table th {
  background-color: #fafbfc;
  color: #2c3e50;
  font-weight: 600;
  border-bottom: 2px solid #e6e6e6;
}

.panel-content ::v-deep .el-table td {
  border-bottom: 1px solid #f0f0f0;
}

.panel-content ::v-deep .el-table--striped .el-table__body tr.el-table__row--striped td {
  background-color: #fafbfc;
}

.panel-content ::v-deep .el-table__row:hover td {
  background-color: #e8f4fd !important;
}

/* 搜索表单样式 */
.panel-header .el-form {
  background: white;
  padding: 15px;
  border-radius: 6px;
  margin-top: 15px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

/* 按钮样式优化 */
.panel-content ::v-deep .el-button--mini {
  padding: 5px 10px;
  border-radius: 4px;
  font-size: 12px;
}

.panel-content ::v-deep .el-button--primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
}

.panel-content ::v-deep .el-button--success {
  background: linear-gradient(135deg, #56ab2f 0%, #a8e6cf 100%);
  border: none;
}

/* 标签样式优化 */
.panel-content ::v-deep .el-tag {
  border-radius: 12px;
  padding: 0 8px;
  font-size: 12px;
}

.panel-content ::v-deep .el-tag--success {
  background: linear-gradient(135deg, #56ab2f 0%, #a8e6cf 100%);
  border: none;
  color: white;
}

.panel-content ::v-deep .el-tag--info {
  background: linear-gradient(135deg, #bdc3c7 0%, #2c3e50 100%);
  border: none;
  color: white;
}

/* 分页样式 */
.panel-content ::v-deep .el-pagination {
  text-align: center;
  padding: 15px 0;
}

/* 分割面板样式 */
::v-deep .splitpanes__pane {
  background: transparent;
}

::v-deep .splitpanes__splitter {
  background: #e6e6e6;
  position: relative;
}

::v-deep .splitpanes__splitter:before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 100%;
  height: 30px;
  background: #667eea;
  border-radius: 3px;
  opacity: 0;
  transition: opacity 0.3s;
}

::v-deep .splitpanes__splitter:hover:before {
  opacity: 0.3;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .drawer-container {
    padding: 5px;
  }
  
  .dept-panel, .user-panel {
    margin: 5px;
  }
  
  .panel-header {
    padding: 10px 15px;
  }
  
  .panel-content {
    padding: 10px;
  }
}
</style>
